<template>
  <div class="page none-sizing">
    <div class="jp-table">
      <vxe-toolbar ref="tPurchaseContractToolbar" :refresh="{query: refreshList}" import export print custom>
        <template #buttons>
          <el-button @click="showSyncDialog(1)">同步合同</el-button>

          <el-button v-if="hasPermission('contract:tPurchaseContract:add')" type="primary" icon="plus" @click="add()">新增合同</el-button>
          <el-button v-if="hasPermission('contract:tPurchaseContract:edit')" type="warning" icon="edit-filled" @click="edit()"
            v-show="$refs.tPurchaseContractTable && $refs.tPurchaseContractTable.getCheckboxRecords().length === 1" plain>修改</el-button>
          <el-button v-if="hasPermission('contract:tPurchaseContract:del')" type="danger" icon="del-filled" @click="del()"
            v-show="$refs.tPurchaseContractTable && $refs.tPurchaseContractTable.getCheckboxRecords().length > 0" plain>删除</el-button>
        </template>
        <template #tools>
          <vxe-button type="text" :title="
		    searchVisible ? '收起检索' : '展开检索'
		  " icon="vxe-icon-search" class="tool-btn" @click="searchVisible = !searchVisible"></vxe-button>
          <vxe-button type="text" title="下载导入模板" v-if="hasPermission('contract:tPurchaseContract:import')" icon="vxe-button--icon vxe-icon-file-excel"
            class="tool-btn m-l-0" @click="downloadTpl()">
          </vxe-button>
        </template>
      </vxe-toolbar>
      <div class="jp-table-body">
        <vxe-table border auto-resize resizable height="600" :loading="loading" size="small" ref="tPurchaseContractTable" show-header-overflow
          highlight-hover-row :menu-config="{}" :print-config="{}" :import-config="{
    importMethod: importMethod,
    types: ['csv', 'xls', 'xlsx'],
    remote: true,
  }" :export-config="{
    remote: true,
    filename: `合同台账数据${moment(new Date()).format(
		'YYYY-MM-DD'
    )}`,
    sheetName: '合同台账数据',
    exportMethod: exportMethod,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all'],
  }" @sort-change="sortChangeHandle" :sort-config="{remote:true}" :data="dataList" :checkbox-config="{}">
          <vxe-column type="seq" width="40"></vxe-column>
          <vxe-column type="checkbox" width="40px"></vxe-column>

          <vxe-column field="contractName" sortable title="合同名称" width="300px">
          </vxe-column>
          <vxe-column field="contractNo" sortable title="合同编号 " width="200px">
          </vxe-column>

          <vxe-column field="supplier.companyName" sortable title="委托方" width="300">
            <template #default="{ row }">
              {{row.supplier && row.supplier.companyName}}
            </template>
          </vxe-column>
          <vxe-column field="contractFeature" sortable title="合同性质（收入/支出）">
            <template #default="{ row }">
              {{ $dictUtils.getDictLabel("contract_feature", row.contractFeature, '-') }}
            </template>
          </vxe-column>
          <!-- <vxe-column field="contractType" sortable title="合同类型">
            <template #default="{ row }">
              {{ $dictUtils.getDictLabel("contract_type", row.contractType, '-') }}
            </template>
          </vxe-column> -->
          <vxe-column field="contractAmount" sortable title="合同金额（元）" align="right">
          </vxe-column>

          <vxe-column field="taxRate" sortable title="税率(%)" align="right">
          </vxe-column>
          <vxe-column field="taxAmount" sortable title="税额" align="right">
          </vxe-column>
          <vxe-column field="qualityGuaranteeFund" sortable title="质保金" align="right">
          </vxe-column>
          <vxe-column field="contractSignTime" sortable title="合同签订时间">
          </vxe-column>
          <!-- <vxe-column field="contractBeginTime" sortable title="合同生效时间">
          </vxe-column>
          <vxe-column field="contractEndTime" sortable title="合同结束时间">
          </vxe-column>
          <vxe-column field="attachment" sortable title="附件">
            <template #default="{ row }">
              <div @click="previewFiles(row.attachment)" class="file">{{getFileName(row.attachment)}}</div>
            </template>
          </vxe-column> -->

          <!-- <vxe-column field="remark" sortable title="备注">
          </vxe-column> -->

          <vxe-column fixed="right" align="center" width="300" title="操作">
            <template #default="{ row }">
              <el-button v-if="hasPermission('contract:tPurchaseContract:view')" type="primary" text icon="view-filled" @click="view(row.id)">查看</el-button>
              <el-button v-if="hasPermission('contract:tPurchaseContract:edit')" type="primary" text icon="edit-filled" @click="edit(row.id)">修改</el-button>
              <el-button v-if="hasPermission('contract:tPurchaseContract:del')" type="danger" text icon="del-filled" @click="del(row.id)">删除</el-button>
              <el-popconfirm title="确认解除合同绑定吗?" @confirm="bindUnbindContract(row.contractNo)" width="260px">
                <template #reference>
                  <el-button type="warning" text>解除合同</el-button>
                </template>
              </el-popconfirm>

            </template>
          </vxe-column>
        </vxe-table>
        <vxe-pager background size="small" :current-page="tablePage.currentPage" :page-size="tablePage.pageSize" :total="tablePage.total"
          :page-sizes="[10, 20, 100, 1000, {label: '全量数据', value: 1000000}]" :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
          @page-change="currentChangeHandle">
        </vxe-pager>
      </div>
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <TPurchaseContractForm ref="tPurchaseContractForm" @refreshDataList="refreshList"></TPurchaseContractForm>

    <!-- 引入文件预览组件 -->
    <FilePreview ref="filePreview" />

    <!-- 添加同步合同弹窗 -->
    <el-dialog title="合同同步" v-model="syncDialogVisible" width="500px" :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="sync-dialog-content">
        <div class="input-label">合同编号</div>
        <el-input v-model="contractNo" placeholder="请输入合同编号" class="contract-input"></el-input>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSaveSure">确认并同步</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- <el-dialog
      v-model="syncDialogVisible"
      title="同步合同"
      width="900px"
      :destroy-on-close="true"
    >
      <div class="sync-dialog-content">
        <vxe-table
          ref="syncTable"
          border
          height="500"
          :loading="syncLoading"
          :data="maskList"
          :radio-config="{}" 
          :checkbox-config="{ isRadio: true }"
        >
          <vxe-column type="radio" width="40"></vxe-column>
          <vxe-column field="contractName" title="合同名称"></vxe-column>
          <vxe-column field="contractNo" title="合同编号"></vxe-column>
          <vxe-column field="supplier.companyName" title="委托方">
            <template #default="{ row }">
              {{row.supplier && row.supplier.companyName}}
            </template>
          </vxe-column>
          <vxe-column field="contractAmount" title="合同金额（元）"></vxe-column>
          <vxe-column field="contractSignTime" title="合同签订时间"></vxe-column>
        </vxe-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="syncDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSyncSave" :loading="saveLoading">
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog> -->
  </div>
</template>

<script>
import TPurchaseContractForm from './TPurchaseContractForm'
import contractService from '@/api/contract/tPurchaseContractService'
// import tPurchaseContractService from '@/api/contract/contractService '
import GridSelect from '@/components/gridSelect'
import purchaseService from '@/api/purchase/purchaseService'
import projectMainService from '@/api/project/projectMainService'
import FilePreview from '@/components/preview'
export default {
  inject: {
    projectId: {
      default: ''
    }
  },
  data() {
    return {
      searchVisible: true,
      contractNo: "",
      searchForm: {
        purchase: {
          id: ''
        },
        project: {
          id: ''
        },
        contractName: '',
        contractNo: '',
        contractFeature: '1',
        contractType: '',
        contractSignTime: '',
        isScientificResearch: ''
      },
      purchaseService: purchaseService,
      projectMainService: projectMainService,
      dataList: [],
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        orders: [{ column: "a.create_time", asc: false }],
      },
      loading: false,
      maskList: [],
      syncDialogVisible: false,
      syncLoading: false,
      saveLoading: false,
      contractShowType: 1
    }
  },
  components: {
    GridSelect,
    TPurchaseContractForm,
    FilePreview
  },
  created() {
    this.searchForm.project.id = this.projectId;
    this.refreshList()
  },
  mounted() {
    this.$nextTick(() => {
      // 将表格和工具栏进行关联
      const $table = this.$refs.tPurchaseContractTable
      const $toolbar = this.$refs.tPurchaseContractToolbar
      $table.connect($toolbar)
    })
  },

  methods: {
    showSyncDialog(type) {
      if (this.dataList.length > 0) {
        this.$message.warning('您需要先解绑已存在的合同')
      } else {
        this.syncDialogVisible = true;
        this.contractShowType = type
      }
      // this.syncLoading = true


      // contractService.list({
      //   'current': 1,
      //   'size': 1000,
      //   'orders': [{ column: "a.create_time", asc: false }],
      //   'contractFeature': 1
      // }).then((data) => {

      //   this.maskList = data.records || []
      //   this.syncDialogVisible = true
      //   this.syncLoading = false
      // }).catch(() => {
      //   this.syncLoading = false
      //   this.$message.error('获取合同数据失败')
      // })
    },
    previewFiles(url) {
      this.$refs.filePreview.open(url)
    },
    bindUnbindContract(id) {
      contractService.unbindContract({ contractNo: id }).then(res => {
        this.$message.success('解绑成功')
        this.refreshList();
      })
    },
    // 获取数据列表
    refreshList(contractFeature) {
      this.loading = true
      contractService.list({
        'current': this.tablePage.currentPage,
        'size': this.tablePage.pageSize,
        'orders': this.tablePage.orders,
        beginContractSignTime: this.searchForm.contractSignTime[0],
        endContractSignTime: this.searchForm.contractSignTime[1],
        'contractFeature': 1,
        ...this.lodash.omit(this.searchForm, 'contractSignTime')
      }).then((data) => {
        this.dataList = data.records
        this.tablePage.total = data.total
        this.loading = false
      })
    },
    // 当前页
    currentChangeHandle({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.refreshList()
    },
    // 排序
    sortChangeHandle(obj) {
      this.tablePage.orders = [];
      if (obj.order != null) {
        this.tablePage.orders = [{ column: obj.column.sortBy || this.$utils.toLine(obj.property), asc: obj.order === "asc" }];
      } else {
        this.tablePage.orders = [{ column: "a.create_time", asc: false }];
      }
      this.refreshList();
    },
    // 新增
    add() {
      if (this.dataList.length > 0) {
        this.$message.warning('您需要先解绑已存在的合同')
      } else {
        this.$refs.tPurchaseContractForm.init('add', this.searchForm.project.id)
      }

    },
    // 修改
    edit(id) {
      id = id || this.$refs.tPurchaseContractTable.getCheckboxRecords().map(item => {
        return item.id
      })[0]
      this.$refs.tPurchaseContractForm.init('edit', id)
    },
    // 查看
    view(id) {
      this.$refs.tPurchaseContractForm.init('view', id)
    },
    // 删除
    del(id) {
      let ids = id || this.$refs.tPurchaseContractTable.getCheckboxRecords().map(item => {
        return item.id
      }).join(',')
      this.$confirm(`确定删除所选项吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        contractService.delete(ids).then((data) => {
          this.$message.success(data)
          this.refreshList()
          this.loading = false
        })
      })
    },
    // 下载模板
    downloadTpl() {
      this.loading = true
      contractService
        .exportTemplate({ contractFeature: 1 })
        .then((data) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(data, "合同台账导入模板");
          this.loading = false
        })
        .catch(function (err) {
          this.loading = false
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    getFileName(attachment) {
      if (!attachment) return '';
      if (attachment.indexOf('&fileName=') != -1) {
        return attachment
          .split(',')
          .map(item => {
            const arr = item.split('&fileName=');
            return arr.length > 1 ? arr[1] : '';
          })
          .filter(Boolean)
          .join(', ');
      } else {
        return attachment
          .split(',')
          .map(item => {
            const arr = item.split('&name=');
            return arr.length > 1 ? arr[1] : '';
          })
          .filter(Boolean)
          .join(', ');
      }

    },
    // 自定义服务端导入
    importMethod({ file }) {
      // 处理表单
      const formBody = new FormData();
      formBody.append("file", file);
      this.loading = true
      contractService.importExcel(formBody).then((result) => {
        this.$message.success({
          dangerouslyUseHTMLString: true,
          message: result,
        });
        this.refreshList();
      });
    },
    // 自定义服务端导出
    exportMethod({ options }) {
      // 传给服务端的参数
      const params = {
        current: this.tablePage.currentPage,
        size: this.tablePage.pageSize,
        orders: this.tablePage.orders,
        ...this.searchForm,
        filename: options.filename,
        sheetName: options.sheetName,
        isHeader: options.isHeader,
        original: options.original,
        mode: options.mode,
        selectIds:
          options.mode === "selected"
            ? options.data.map((item) => item.id)
            : [],
        contractFeature: 1,
        exportFields: options.columns.map(
          (column) => column.property && column.property.split(".")[0]
        ),
      };
      this.loading = true;
      return contractService
        .exportExcel(params)
        .then((data) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(data, options.filename);
          this.loading = false;
        })
        .catch(function (err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.refreshList()
    },
    // 保存同步数据
    handleSyncSave() {
      // 获取单选选中的行
      const selectedRow = this.$refs.syncTable.getRadioRecord()

      if (!selectedRow) {
        this.$message.warning('请选择需要同步的合同')
        return
      }

      this.saveLoading = true

      // 为选中的数据添加projectId
      const syncData = {
        ...selectedRow,
        project: {
          id: this.searchForm.project.id
        }
      }
      // 调用保存接口
      contractService.save(syncData).then(() => {
        this.$message.success('同步成功')
        this.syncDialogVisible = false
        this.refreshList() // 刷新列表
        this.saveLoading = false
      }).catch(() => {
        this.$message.error('同步失败')
        this.saveLoading = false
      })
    },
    handleSaveSure() {
      this.saveLoading = true;
      const syncData = {
        projectId: this.searchForm.project.id,
        contractNo: this.contractNo
      }

      if (this.contractShowType == 1) {
        contractService.bindingContract(syncData).then((data) => {

          if (data == '没有此合同') {
            this.$message.error('没有此合同')
          } else {
            this.$message.success('同步成功')
            this.syncDialogVisible = false
            this.refreshList() // 刷新列表
            this.saveLoading = false
          }

        }).catch(() => {
          this.$message.error('同步失败')
          this.saveLoading = false
        })
      } else {
        contractService.bindingContract(syncData).then((data) => {

          if (data == '没有此合同') {
            this.$message.error('没有此合同')
          } else {
            this.$message.success('同步成功')
            this.syncDialogVisible = false
            this.refreshList() // 刷新列表
            this.saveLoading = false
          }

        }).catch(() => {
          this.$message.error('同步失败')
          this.saveLoading = false
        })
      }




    }
  }
}
</script>

<style lang="scss" scoped>
.sync-dialog-content {
  .vxe-table {
    margin-bottom: 10px;
  }
}

.dialog-footer {
  text-align: right;
  margin-top: 10px;
}
</style>

